﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using HtmlAgilityPack;

namespace MetroLightKit.ConvertSvg
{
    public class HtmlUtils
    {
        public static void RequestTest(string requestUri, string outDirectoryPath, string xpathSvgNodes, string xpathNameRelativeNodeSvg)
        {
            WebRequest request = WebRequest.Create(requestUri);
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var dataStream = response.GetResponseStream())
                {
                    if (dataStream != null)
                    {
                        using (var reader = new StreamReader(dataStream))
                        {
                            Test(reader, outDirectoryPath, xpathSvgNodes, xpathNameRelativeNodeSvg);
                        }
                    }
                }
            }
        }
        public static void Test(StreamReader html, string outDirectoryPath, string xpathSvgNodes, string xpathNameRelativeNodeSvg)
        {
            var outDirectory = new DirectoryInfo(outDirectoryPath);
            if(!outDirectory.Exists)
                outDirectory.Create();

            var doc = new HtmlDocument();
            //doc.Load(@"C:\Users\PAU\Desktop\HtmlAgilityPack\sgv.html");
            doc.Load(html);

            var col = doc.DocumentNode.SelectNodes(xpathSvgNodes);
            foreach (var node in col)
            {
                try
                {
                    var svg = node.OuterHtml;
                    //var name = node.Ancestors().First().SelectSingleNode(@".//a[@class='noun-name']").InnerText;
                    var name = node.SelectSingleNode(xpathNameRelativeNodeSvg).InnerText;

                    using (var file = File.CreateText(Path.Combine(outDirectory.FullName, name + ".svg")))
                    {
                        file.Write(svg);
                    }
                }
                catch (Exception)
                {
                    
                }

            }
        }
    }
}
